package com.worklog.controller;

import java.io.IOException;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.worklog.model.User;
import com.worklog.service.UserService;
import com.worklog.util.PasswordHelper;
import com.worklog.util.ResultData;
import com.worklog.util.VerifyCode;
import com.worklog.util.VerifyCodeUtil;

import lombok.extern.slf4j.Slf4j;

@RestController
@Slf4j
@RequestMapping("/anon")
public class AnonController {
	@Resource
	private UserService userService;

	@RequestMapping(value = "/getVerifyCodeImage")
	public void getVerifyCodeImage(HttpServletRequest request, HttpServletResponse response) throws IOException {
		// 设置页面不缓存
		response.setHeader("Pragma", "no-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0);
		String verifyCode = VerifyCode.generateVerifyCode(VerifyCodeUtil.TYPE_NUM_ONLY, 4, null);
		// 将验证码放到HttpSession里面
		request.getSession().setAttribute("verifyCode", verifyCode);
		// 设置输出的内容的类型为JPEG图像
		response.setContentType("image/jpeg");
		int w = 70, h = 25;
		VerifyCode.outputImage2(w, h, 0, response.getOutputStream(), verifyCode);
	}

	@RequestMapping(value = "/add", method = RequestMethod.POST)
	public ResultData add(User user) {
		ResultData result = new ResultData();
		try {
			User u = userService.selectByUsername(user.getUsername());

			if (u != null) {
				result.error("用户名已存在!", null);
				return result;
			}
			user.setEnable(1);
			PasswordHelper passwordHelper = new PasswordHelper();
			passwordHelper.encryptPassword(user);
			userService.save(user);
			result.success(" ");
		} catch (Exception e) {
			log.error(e.getMessage());
			result.error(e.getMessage(), e);
		}
		return result;
	}

	@RequestMapping(value = "/verifyUsername")
	public ResultData verifyUsername(@RequestParam(value = "username", required = true) String username) {
		ResultData result = new ResultData();
		try {
			User u = userService.selectByUsername(username);
			if (u != null) {
				result.error("用户名已存在", null);
			}
		} catch (Exception e) {
			log.error(e.getMessage());
			result.error(e.getMessage(), e);
		}
		return result;
	}
}
